package com.qyhl.webtv.module_news.news.catchnews;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.entity.news.CatchSmallBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MJavascriptInterface;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.coin.GoldCoinTimeView;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.MyListView;
import com.qyhl.webtv.commonlib.utils.view.MyWebView;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.module_news.utils.MyLoadingLayout;
import com.qyhl.webtv.module_news.utils.NewsConstant;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/11/30.
 * 抓取新闻详情
 */
@Route(path = ARouterPathConstant.NEWS_CATCH)
public class CatchNewsActivity extends BaseActivity implements CatchNewsContract.CatchNewsView, BaseActivity.InputListener {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.webview)
    MyWebView webview;
    @BindView(R2.id.listview)
    MyListView listview;
    @BindView(R2.id.comment_layout)
    LinearLayout commentLayout;
    @BindView(R2.id.comment_mask)
    LoadingLayout commentMask;
    @BindView(R2.id.scrollview)
    ScrollView scrollview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    MyLoadingLayout loadMask;
    @BindView(R2.id.editbar)
    EditBar editbar;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.coin_time_view)
    GoldCoinTimeView coinTimeView;
    @BindView(R2.id.adv_layout)
    RelativeLayout advLayout;
    @BindView(R2.id.coin_layout)
    CardView coinLayout;
    @BindView(R2.id.coin_login_tips)
    ImageView coinLoginTips;
    @BindView(R2.id.adv_cover)
    ImageView advCover;
    @BindView(R2.id.adv_title)
    TextView advTitle;
    @BindView(R2.id.scan)
    TextView scan;
    @BindView(R2.id.publish_date)
    TextView publishDate;
    @BindView(R2.id.origin_writer)
    TextView originWriter;

    private boolean editbarEnabled = true;
    String newsId;

    private CatchNewsPresenter mPresenter;

    private CatchSmallBean mBean;

    private List<CatchSmallBean.Comments> mList;

    private int page = 1;

    private Intent intent;

    private String comment, time;

    private RequestOptions options;

    private CommonAdapter<CatchSmallBean.Comments> commonAdapter;

    private int commentRule;//审核模式

    private boolean isLimited = false;

    /**
     * 是否第一次进入，用于设置金币转圈状态
     */
    private boolean isFirst = true;

    private boolean isCurFirst = true;


    private String advSwitch;

    private String integralSwitch;

    /**
     * 广告是否已经显示
     */
    private boolean isShowed = false;
    /**
     * 获取金币的类型
     */
    private int mCoinType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_news_catch;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        setSupportActionBar(toolbar);
        mPresenter = new CatchNewsPresenter(this);
        advSwitch = CommonUtils.getInstance().getOtherAdv();
        integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        newsId = getIntent().getStringExtra("id");
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.count(newsId);
        mPresenter.getDetail(newsId);
    }

    /**
     * 初始化
     */
    private void initView() {

        addInputListener(this);
        loadMask.setStatus(LoadingLayout.Loading);

        mList = new ArrayList<>();


        //配置刷新头
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);
        refresh.setDisableContentWhenLoading(true);
        refresh.setDisableContentWhenRefresh(true);

        //隐藏进入评论和收藏按钮
        editbar.hideComment(true);
        editbar.hideCollect(true);
        editbar.setBackground(R.color.white);

        //glide配置
        options = new RequestOptions()
                .centerCrop()
                .transform(new GlideCircleTransform(this))
                .placeholder(R.drawable.comment_head_default)
                .error(R.drawable.comment_head_default);

        listview.setAdapter(commonAdapter = new CommonAdapter<CatchSmallBean.Comments>(this, R.layout.news_item_comment, mList) {
            @Override
            protected void convert(ViewHolder viewHolder, CatchSmallBean.Comments item, int position) {
                viewHolder.setText(R.id.nickName, item.getNickName());
                viewHolder.setText(R.id.content, item.getContent());
                viewHolder.setText(R.id.publish_date, DateUtils.mTranslateDate(item.getCareateTime()));
                ImageView headIcon = viewHolder.getView(R.id.head_icon);

                Glide.with(getApplicationContext())
                        .load(item.getUserAvatar())
                        .apply(options)
                        .into(headIcon);
            }
        });

        if (advSwitch.equals("1")) {
            advLayout.setVisibility(View.GONE);
        } else {
            advLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        advCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        coinTimeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RouterManager.router(ARouterPathConstant.ANTIC);
            }
        });
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPresenter.getDetail(newsId);
            }
        });

        //加载
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mPresenter.getComment(page + "", "10", newsId);
            }
        });

        //重载
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getDetail(newsId);
            }
        });

        //评论重载
        commentMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                commentMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getComment(page + "", "10", newsId);
            }
        });
        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (editbarEnabled) {
                    editbarEnabled = false;

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                comment = editbar.getContent();
                                if (StringUtils.isEmpty(comment)) {
                                    Toasty.normal(CatchNewsActivity.this, "评论不能为空！", Toast.LENGTH_SHORT).show();
                                } else {
                                    String nickName = CommonUtils.getInstance().getNickName();
                                    String userName = CommonUtils.getInstance().getUserName();
                                    String headicon = CommonUtils.getInstance().getUserLogo();
                                    mPresenter.sendComment(newsId, comment, userName, nickName, headicon);
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    time = simpleDateFormat.format(new Date());
                                    hideInput();//隐藏软键盘
                                }
                                editbar.clearContent();
                            } else {
                                Toasty.normal(CatchNewsActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                RouterManager.routerLogin(CatchNewsActivity.this, 0);
                            }
                            editbarEnabled = true;
                        }

                        @Override
                        public void error(String s) {
                            editbarEnabled = true;
                        }
                    });

                }
            }

            @Override
            public void onShare() {
                toShare();
            }
        });

        final Rect scrollBounds = new Rect();
        scrollview.getHitRect(scrollBounds);


        loadMask.setTouchEventListener(() -> {
            if (integralSwitch.equals("1")) {
                coinTimeView.setVisibility(View.VISIBLE);
                if (!isLimited && (Hawk.contains("login") || isFirst || isCurFirst)) {
                    coinTimeView.beginTime();
                }
                if (advLayout.getLocalVisibleRect(scrollBounds) && !isShowed) {
                    isShowed = true;
                }
            }
        });

        if (integralSwitch.equals("1")) {
            coinLayout.setVisibility(View.VISIBLE);
            coinTimeView.setOnTimeoutListener(new GoldCoinTimeView.OnTimeoutListener() {
                @Override
                public void timeout() {
                    if (Hawk.contains("login")) {
                        mCoinType = 1;
                        mPresenter.getCoin("0", "readNews", 1);
                    } else if (isFirst) {
                        coinLoginTips.setVisibility(View.GONE);
                        isFirst = false;
                        isCurFirst = false;
                        coinTimeView.stopTime();
                        coinTimeView.resetMax();
                    } else {
                        coinTimeView.stopTime();
                        isCurFirst = false;
                        coinTimeView.resetMax();
                    }
                }

                @Override
                public void limit() {
                    coinTimeView.stopTime();
                    isLimited = true;
                }
            });
        } else {
            coinLayout.setVisibility(View.GONE);
        }


    }

    /**
     * 分享
     */
    private void toShare() {
        MPermissionUtils.requestPermissionsResult(CatchNewsActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                MShareBoard shareBoard = new MShareBoard(CatchNewsActivity.this, newsId, mBean.getNewsDetail().getTitle(), mBean.getNewsDetail().getCover(), "", CommonUtils.getInstance().getBannerId(), 3);
                shareBoard.showPopupWindow();
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(CatchNewsActivity.this);
            }
        });
    }


    /**
     * 设置详情
     *
     * @param bean
     */
    @Override
    public void setDetail(CatchSmallBean bean) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        mBean = bean;

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getNewsDetail().getId() + "", mBean.getNewsDetail().getTitle(), mBean.getNewsDetail().getType(), "0");
        }
        //审核模式
        commentRule = mBean.getCommentRule();

        //设置作者和来源
        if (StringUtils.isEmpty(mBean.getNewsDetail().getSource())) {
            originWriter.setText(mBean.getNewsDetail().getAutor());
        } else {
            originWriter.setText(mBean.getNewsDetail().getSource() + "\t\t\t" + mBean.getNewsDetail().getAutor());
        }
        //设置发布时间
        publishDate.setText(DateUtils.detailDateTranslate(mBean.getNewsDetail().careateTime));

        //设置浏览数
        try {

            int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
            if (minPlay == 0) {
                scan.setVisibility(View.GONE);
            } else {
                //判断评论数是否大于最少浏览数
                if (StringUtils.isEmpty(mBean.getNewsDetail().getClickCount() + "")) {
                    scan.setVisibility(View.GONE);
                } else if (mBean.getNewsDetail().getClickCount() >=
                        minPlay) {
                    scan.setText(StringUtils.transformNum(mBean.getNewsDetail().getClickCount() + ""));
                    scan.setVisibility(View.VISIBLE);
                } else {
                    scan.setVisibility(View.GONE);
                }
            }

        } catch (Exception e) {
            scan.setVisibility(View.GONE);
        }

        //配置详情
        title.setText(mBean.getNewsDetail().getTitle() == null ? "" : mBean.getNewsDetail().getTitle());
        showContent(mBean.getNewsDetail().getContent());
        if (mBean.getComments() != null && mBean.getComments().size() > 0) {
            setComment(mBean.getComments(), false, false);
        } else {
            setCommentEmpty("暂无任何评论!");
        }
    }


    //展示内容
    private void showContent(String content) {
        loadMask.setStatus(LoadingLayout.Success);
        initWebView();
        if (StringUtils.isNotEmpty(content)) {
            String htmlString = getNewContent(content);
            webview.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
            webview.addJavascriptInterface(new MJavascriptInterface(this, StringUtils.returnImageUrlsFromHtml(htmlString)), "imagelistener");
            webview.setWebViewClient(new MyWebViewClient());

            removeWebViewJI(webview);
        } else {
            setError("出错啦，点击重新加载！");
        }

    }

    //初始化webview
    private void initWebView() {
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDefaultTextEncodingName("utf-8");
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setFontSize(SpfManager.getInstance(this).getInt("fontSize", 2));
        webview.getSettings().setBlockNetworkImage(true);
    }

    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        editbar.changeStateDefault(this);
    }


    //Web视图
    class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webview.getSettings().setBlockNetworkImage(true);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            loadMask.setStatus(LoadingLayout.Success);
            loadMask.setReloadButtonText("点击重试~~");
            /*
             * 非wifi下不加载图片
             */
            if (NetUtil.isWifi(CatchNewsActivity.this)) {
                webview.getSettings().setBlockNetworkImage(false);
            } else {
                if (SpfManager.getInstance(CatchNewsActivity.this).getBoolean("noPicture", false)) {
                    webview.getSettings().setBlockNetworkImage(true);
                } else {
                    webview.getSettings().setBlockNetworkImage(false);
                }
            }
            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webview.measure(w, h);
            addImageClickListener(view);
        }

        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        private void addImageClickListener(WebView webView) {
            webView.loadUrl(
                    "javascript:(function(){"
                            + "  var objs = document.getElementsByTagName(\"img\"); "
                            + "  for(var i=0;i<objs.length;i++){"
                            + "     objs[i].onclick=function(){"
                            + "          window.imagelistener.openImage(this.src);  "
                            + "     }"
                            + "  }"
                            + "})()");
        }
    }

    //webview中的图片自适应大小
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("max-width", "100%").attr("max-height", "auto");
            element.attr("style", "");
        }

        Elements elements1 = doc.getElementsByTag("video");
        for (Element element : elements1) {
            element.attr("width", "100%").attr("height", "auto");
        }


        doc.select("div.titleDivs").remove();

        Log.i("VACK", doc.toString());
        return doc.toString();
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setEmptyText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 加载出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 设置评论
     *
     * @param beanList
     * @param isMore
     */
    @Override
    public void setComment(List<CatchSmallBean.Comments> beanList, boolean isMore, boolean isSelf) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        commentMask.setStatus(LoadingLayout.Success);
        commentMask.setReloadButtonText("点击重试~~");
        refresh.setEnableLoadMore(true);

        if (isSelf) {
            mList.addAll(0, beanList);
        } else {
            page++;
            if (isMore) {
                mList.addAll(beanList);
            } else {
                mList.clear();
                mList.addAll(beanList);
            }
        }

        commonAdapter.notifyDataSetChanged();
    }

    /**
     * 评论获取出错
     *
     * @param msg
     */
    @Override
    public void setCommentError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        refresh.setEnableLoadMore(false);
        commentMask.setStatus(LoadingLayout.Error);
        commentMask.setErrorText(msg);
        commentMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无评论
     *
     * @param msg
     */
    @Override
    public void setCommentEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        refresh.setEnableLoadMore(false);
        commentMask.setEmptyText(msg);
        commentMask.setEmptyImage(R.drawable.empty_comment);
        commentMask.setStatus(LoadingLayout.Empty);
        commentMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 评论提示
     *
     * @param msg
     */
    @Override
    public void setCommentMessage(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        refresh.setEnableLoadMore(false);
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        commentMask.setReloadButtonText("点击重试~~");
    }

    /**
     * log
     *
     * @param msg
     */
    @Override
    public void setLog(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        Log.i("news_catch", msg);
        commentMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 评论成功
     *
     * @param msg
     */
    @Override
    public void sendSuccess(String msg) {
        editbar.changeStateDefault(this);
        if (commentRule == 1) {
            String nickName = CommonUtils.getInstance().getNickName();
            Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
            List<CatchSmallBean.Comments> list = new ArrayList<>();
            String userName = CommonUtils.getInstance().getUserName();
            String headicon = CommonUtils.getInstance().getUserLogo();
            list.add(new CatchSmallBean.Comments(Integer.valueOf(newsId), DateUtils.mTranslateDate(time), nickName, 2, userName, comment, 0, headicon));
            setComment(list, false, true);
        } else {
            Toasty.normal(this, "评论成功，等待审核！", Toast.LENGTH_SHORT).show();
        }
        String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        if (integralSwitch.equals("1")) {
            getCoin();
        }

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.commentaryLog(CommonUtils.getInstance().getUserName(), mBean.getNewsDetail().getId() + "", mBean.getNewsDetail().getTitle(), comment);
        }
    }

    private void getCoin() {
        mCoinType = 2;
        mPresenter.getCoin("4", "gainCoin", 2);
    }

    /**
     * 评论失败
     *
     * @param msg
     */
    @Override
    public void sendError(String msg) {
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getCoinSuccess(CoinBean bean) {
        if (mCoinType == 1) {
            coinTimeView.transformation(bean.getCoin() + "", 3);
            if (isLimited) {
                coinTimeView.setEnjoin(true);
                coinTimeView.setProgress(0);
            }
        } else {
            Toasty.normal(CatchNewsActivity.this, "评论成功，获得" + bean.getCoin() + "金币！", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void getCoinFailure(String msg) {
        Log.i("coin", msg);
        if (mCoinType == 1) {
            coinTimeView.stopTime();
            coinTimeView.setEnjoin(true);
        } else {
            Log.e("error_comment", msg);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (editbar.getType() == EditBar.TYPE_SEND) {//判断是否是输入状态，是则返回初始状态，否则退出
                    editbar.changeStateDefault(this);
                    return true;
                } else if (webview != null && webview.canGoBack()) {
                    webview.goBack();
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("抓取详情");
        MobclickAgent.onResume(this);
        ActionLogUtils.getInstance().onResume(this, ActionConstant.NEWSDETAIL);
        if (integralSwitch.equals("1")) {
            coinTimeView.setRepeat(false);
            if (isLimited) {
                coinTimeView.setEnjoin(true);
                coinTimeView.setProgress(0);
            } else if (Hawk.contains("login")) {

                if (NewsConstant.curProgress != 0) {
                    coinTimeView.setProgress(NewsConstant.curProgress);
                }
                coinTimeView.beginTime();
            } else {
                isFirst = SpfManager.getInstance(this).getBoolean("isFirst", true);
                if (SpfManager.getInstance(this).getBoolean("isFirst", true)) {
                    coinLoginTips.setVisibility(View.VISIBLE);
                    SpfManager.getInstance(this).putBoolean("isFirst", false);
                    coinTimeView.beginTime();
                } else {
                    coinLoginTips.setVisibility(View.GONE);
                }
            }
        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("抓取详情");
        MobclickAgent.onPause(this);
        ActionLogUtils.getInstance().onPause(this, ActionConstant.NEWSDETAIL);
        if (Hawk.contains("login") && integralSwitch.equals("1")) {
            NewsConstant.curProgress = coinTimeView.getProgress();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.removeAllViews();
            webview.destroy();
        }
        if (Hawk.contains("login") && integralSwitch.equals("1")) {
            coinTimeView.stopTime();
        }

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getNewsDetail().getId() + "", mBean.getNewsDetail().getTitle(), mBean.getNewsDetail().getType(), "1");
        }
    }


    /**
     * 设置webview字体大小
     */
    private void setFontSize(int position) {
        switch (position) {
            case 0:
                webview.getSettings().setTextZoom(50);
                break;
            case 1:
                webview.getSettings().setTextZoom(75);
                break;
            case 2:
                webview.getSettings().setTextZoom(100);
                break;
            case 3:
                webview.getSettings().setTextZoom(150);
                break;
            case 4:
                webview.getSettings().setTextZoom(200);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        } else if (item.getItemId() == R.id.more) {
            MShareBoard shareBoard = new MShareBoard(CatchNewsActivity.this, newsId, mBean.getNewsDetail().getTitle(), mBean.getNewsDetail().getCover(), "", CommonUtils.getInstance().getBannerId(), 3, false, false);
            shareBoard.setToolListener(new MShareBoard.ShareToolListener() {
                @Override
                public void collectChange(boolean isCollect) {

                }

                @Override
                public void textSizeChange() {
                    int checkId;
                    switch (SpfManager.getInstance(CatchNewsActivity.this).getInt("fontSize", 2)) {
                        case 0:
                            checkId = R.id.textsize_lv1;
                            break;
                        case 1:
                            checkId = R.id.textsize_lv2;
                            break;
                        case 2:
                            checkId = R.id.textsize_lv3;
                            break;
                        case 3:
                            checkId = R.id.textsize_lv4;
                            break;
                        case 4:
                            checkId = R.id.textsize_lv5;
                            break;
                        default:
                            checkId = R.id.textsize_lv3;
                            break;
                    }
                    new OtherDialog.Builder(CatchNewsActivity.this)
                            .setContentView(R.layout.news_dialog_textsize_choice)
                            .setWidth(0.8f)
                            .setCanceledOnTouchOutside(true)
                            .setOnCheckedChangeListener(R.id.dialog_radioGroup, checkId, new OtherDialog.CheckedChangeListener() {
                                @Override
                                public void checkedChange(int position) {

                                    int pos = 0;
                                    if (position == R.id.textsize_lv1) {
                                        pos = 0;
                                    } else if (position == R.id.textsize_lv2) {
                                        pos = 1;
                                    } else if (position == R.id.textsize_lv3) {
                                        pos = 2;
                                    } else if (position == R.id.textsize_lv4) {
                                        pos = 3;
                                    } else if (position == R.id.textsize_lv5) {
                                        pos = 4;
                                    }

                                    SpfManager.getInstance(CatchNewsActivity.this).putInt("fontSize", pos);
                                    setFontSize(pos);
                                }
                            })
                            .setDismissButton(R.id.dialog_cancel)
                            .show();
                }
            });
            shareBoard.showPopupWindow();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.news_detail_mores, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
